// pages/confirm_car/confirm_car.js
// pages/confirm_order/confirm_order.js
// 获取应用实例
const app = getApp()
var baseurl = app.baseurl.url;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    yuming: app.yuming.url,
    address: '',
    goods_id: '',
    list: '',
    img: '',
    number: 1,
    message: '',
    shopdata: [],
    cart_id: [],
    res_null: '',
    allprice: '',
    Subtotal: '', // 商品小计
    // freight: '', // 运费
    w_total: '', // 运费总和
    allfreight: '' // 总运费
  },
  getDataBindTap: function (e) {
    var result = e.detail.value;
    this.setData({
      message: result
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // shopdata=[{"goods_id":12,"price":"80.00","number":1,"type":1},{"goods_id":11,"price":"188.00","number":5,"type":1}]&cart_id=33,32

    // 详情列表
    let shopdata = JSON.parse(options.shopdata)
    // console.log('cart_id', options.cart_id);
    this.setData({
      shopdata: shopdata,
      cart_id: options.cart_id.split(","),
      goods_id: options.goods_id
    })
    // this.list(options.goods_id)
    // console.log('shopdata：',this.data.shopdata);
    // console.log(this.data.cart_id);
    this.address()
  },
  address() {
    wx.request({
      url: `${baseurl}/user.UserAddress/get_details`,
      method: 'POST',
      data: {
        status: 1,
        user_id: wx.getStorageSync("user_id"),
      },
      success: (res) => {
        this.setData({
          address: res.data.data,
        })
        this.freight()
      }
    })
  },

  // 运费
  freight() {
    wx.request({
      url: `${baseurl}/order.Order/Freight`,
      method: 'POST',
      data: {
        user_id: wx.getStorageSync("user_id"),
        province: this.data.address.province,
      },
      success: (res) => {
        this.setData({
          res_null: res.data.data
        })
        let result = res

        let price = 0 // 商品小计
        let all_pr = result.data.data  // 总价
        // 判断不用运费的
        if (res.data.data == null) {
          wx.showToast({
            title: '地址暂不配送',
            icon: 'none',
            duration: 2000
          })

          this.data.shopdata.forEach(val => {
            price = price + (val.price * val.number)
          });
          all_pr = price.toFixed(2)
          this.setData({
            allfreight: '地址暂不配送',
            allprice: price,
            Subtotal: all_pr
          })
        } else {

          // 运费
          let First_price = result.data.data.price  // 首件运费
          let lastprice = result.data.data.prices  // 多出的运费
          let sum = 0
          let price = 0 // 商品小计
          let allfreight = 0; // 总运费
          let all_pr = result.data.data  // 总价
          var weight = 0 // 重量
          this.data.shopdata.forEach(val => {
            // console.log('val', val);
            sum = sum + val.number  // 获取件数
            price = price + (val.price * val.number)
            weight = weight + (val.weight * val.number)  // 按重量收费
          });
          // price = price + (val.price * val.number)  // 按重量收费
          all_pr = price.toFixed(2)  // 商品小计

          // 运费改成按照每个省份的首件*1+（n-1）*多余价格
          // allfreight = First_price * 1 + (sum - 1) * lastprice
          // allfreight = allfreight.toFixed(2)  // 按件收费

          // 运费 首重 + (n-1) * 多余价格
          allfreight = parseFloat(First_price) + parseFloat((weight - 1) * lastprice)
          allfreight = allfreight.toFixed(2)  // 按重量收费

          // 总价
          price = parseFloat(price) + parseFloat(allfreight)
          price = price.toFixed(2)



          this.setData({
            // freight: freight ,
            allfreight: allfreight,
            allprice: price,
            Subtotal: all_pr
          })
        }


      }
    })
  },

  add(e) {
    console.log('list', this.data.shopdata);
    e.detail.goods_id
    console.log('add', e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index
    var carts = this.data.shopdata; // 购物车数据
    var num = carts[index].number; // 当前数量
    if (num < 999) {
      num++
      carts[index].number = num;
      this.setData({
        shopdata: carts
      });
      this.freight()
    } else {
      wx.showToast({
        title: '库存不足',
        icon: 'none',
        duration: 2000
      })
    }
  },
  reduce(e) {
    e.detail.goods_id
    // console.log('reduce', e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index
    var carts = this.data.shopdata; // 购物车数据
    var num = carts[index].number; // 当前数量
    if (num > 1) {
      num--
      carts[index].number = num;
      this.setData({
        shopdata: carts
      });
      this.freight()

    } else {
      wx.showModal({
        title: '删除提示',
        content: '是否确定删除？',
        showCancel: true,//是否显示取消按钮
        cancelText: "否",//默认是“取消”
        cancelColor: '#333',//取消文字的颜色
        confirmText: "是",//默认是“确定”
        confirmColor: '#333',//确定文字的颜色
        success: res => {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
            wx.showToast({
              title: '删除失败',
              icon: 'none',
              duration: 2000
            })
          } else {
            //点击确定 
            wx.showToast({
              title: '删除成功',
              icon: 'none',
              duration: 2000
            })
            // console.log(this.data.cart_id);
            var cart_id = this.data.cart_id  // 当前cart_id数组
            var shopdata = this.data.shopdata  // 当前shopdata数组
            cart_id.splice(index, 1) // 删除cart_id
            shopdata.splice(index, 1) // 删除列表
            // console.log('cart_id', car_id);
            // console.log('11', this.data.cart_id);
            // console.log('22', this.data.shopdata);
            this.setData({
              shopdata: shopdata,
              cart_id: cart_id
            })
            this.freight()
          }
        },
        fail: function (res) {
          //接口调用失败的回调函数 
          wx.showToast({
            title: '删除失败',
            icon: 'none',
            duration: 2000
          })
        },

      })
    }
  },
  // 立即支付
  puy() {
    wx.request({
      url: `${baseurl}/order.Order/cartpay`,
      method: 'POST',
      data: {
        user_id: wx.getStorageSync("user_id"),
        openid: wx.getStorageSync("openid"),
        data: this.data.shopdata,
        cart_id: this.data.cart_id,
        user_name: this.data.address.user_name,
        phone: this.data.address.phone,
        province: this.data.address.province,
        city: this.data.address.city,
        area: this.data.address.area,
        address: this.data.address.address,
        message: this.data.message
      },
      success: (res) => {
        console.log(res.data);
        // var appid = getApp().globalData.appid; //appid
        // console.log(appid);
        let timeStamp = res.data.data.data_pay_sign.timeStamp
        let nonceStr = res.data.data.data_pay_sign.nonceStr
        let pack = res.data.data.data_pay_sign.package
        let paySign = res.data.data.data_pay_sign.paySign
        let signType = res.data.data.data_pay_sign.signType
        wx.requestPayment({
          "timeStamp": timeStamp,
          "nonceStr": nonceStr,
          "package": pack,
          "signType": signType,
          "paySign": paySign,
          "success": function (res) {
            // console.log('111', res);
            wx.showToast({
              title: '支付成功',
              // icon: 'none',
              duration: 2000
            })
            // 支付成功
            wx.reLaunch({
              url: '/pages/success/success',
            })
          },
          "fail": function (res) {
            // console.log('222', res);
            wx.showToast({
              title: '支付失败',
              icon: 'none',
              duration: 2000
            })
            // wx.reLaunch({
            //   url: '/pages/order/order'
            // })
            // setTimeout(() => {
            //   wx.reLaunch({
            //     url: '/pages/order/order'
            //   })
            // }, 500);

          },
          "complete": function (res) {
            // 接口调用结束的回调函数（调用成功、失败都会执行）

          }
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.address()
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})